< previous page page_333 next page >

Page 333
Where Is ByVal Used?
The ByVal keyword can appear in two places: in a function declaration or in a function call.
Consider the following two code fragments:
Declare Function SendMessage Lib "User32" Alias "SendMessageA" _
(ByVal Hwnd As Long, ByVal Msg As Long, ByVal wParam As Long, _
ByVal lParam As Long) As Long

Dim myvar As Long
Call SendMessage(hwnd, msg, wparam, myvar)
Look closely at the lParam parameter. The SendMessage function can be used in many different ways, and the lParam parameter can actually refer to many different types of data. In this declaration, the lParam parameter is always a Long value. The myvar variable is declared as a Long here, but it really wouldn't matter if it was declared as a variant or integer or even a string. Visual Basic would convert the value to a Long numeric value as part of the SendMessage call. The declaration specifies the type of the parameter and the way it should be called, so Visual Basic can force the variable to the correct type. In the following declaration, the lParam parameter is specified as the As Any type.
Declare Function SendMessage Lib "User32" Alias "SendMessageA" _
(ByVal Hwnd As Long, ByVal Msg As Long, ByVal wParam As Long, _
lParam As Any) As Long

Dim myvar As Long
Call SendMessage(hwnd, msg, wparam, ByVal myvar)
The As Any term tells Visual Basic that it should perform no type checking on the parameter that is passed. So the data passed to the SendMessage function depends on the type of the variable used in the call. In this case, it is critical that the variable be declared as a Long (if that's the type you wish to pass) because Visual Basic does no error checking or conversion. You also need to specify the ByVal keyword during the call if you wish the call to be made by value.
The As Any parameter type is extremely dangerous. You should avoid using it in your function declarations whenever possible. A far better approach is to create several aliases of a function that each take a particular parameter type. For example, the most common data types for the lParam parameter in the SendMessage function are Longs and strings. You'll find the following two declarations in the api32.txt file on the CD that comes with this book:

 
< previous page page_333 next page >